<?php


/**
 * Builds the template
 *
 * @author Juan
 */

class template {
    
    private $_views_path;
    
    private $_themes; 
    private $_theme;
    private $_theme_default;
    private $_theme_path;
    private $_theme_parts;
    private $_theme_parts_omit = array();
    private $_template_scripts; // Scripts available in the library 
    private $_template_styles; // Styles available in the library 
    
    private $_scripts_default = array();
    private $_scripts_load = array();
    private $_scripts;
    private $_scripts_html;

    private $_styles_default = array();
    private $_styles_load = array();
    private $_styles;
    private $_styles_html;
    
    private $_header; // Data to be outputed in the head
    private $_footer; // Data to be outputed in the foot
    
    private $_footer_html; // Data to be outputed in the foot
    
    private $_ci;
    private $_data;
    
    private $_body;
    
    private $_config;

    
    function __construct($config = array())
    {    
        
        $this->_ci =& get_instance();
        
        $this->_views_path = APPPATH.'views/';
        
        $this->_config = $config;
        
        // Load config file
        $this->_ci->load->config('template', TRUE);
        $this->_themes = $this->_ci->config->item('themes', 'template');
        $this->_template_styles = $this->_ci->config->item('styles', 'template');                           
        $this->_template_scripts = $this->_ci->config->item('scripts', 'template');
        $this->_template_footer = $this->_ci->config->item('footer', 'template');
    }
    
    
    /**
        * Initialize preferences
        *
        * @access	public
        * @param	array
        * @return	void
        */
    function initialize($config = array())
    {

        if(!$config) $config = array();

        // Set theme
        $this->set_theme($config);

        // Get and set default styles and scripts
        $this->set_defaults();

        // Set Scripts
        $this->set_scripts($config);
        // Set Styles
        $this->set_styles($config);
        
        /*
         * test test
         */
        $this->set_footer();
        
        // Include / omit theme parts
        $this->set_theme_parts($config);
        
        // Set header data
        if(array_key_exists('header', $config)) $this->set_header($config['header']);
        // Set footer data
        if(array_key_exists('footer', $config)) $this->set_footer($config['footer']); 

        // Build the html if there are things to load
        if(is_array($this->_scripts)) $this->build_scripts();
        if(is_array($this->_styles)) $this->build_styles();

    }
    
    // Scripts
    function set_scripts($config)
    {
        // Set Scripts to load
        if(array_key_exists('scripts', $config)) $this->set_scripts_load($config['scripts']);
        // Merge scripts to load and defaults
        $this->_scripts = $this->merge_scripts();
        
    }

    function set_scripts_load($scripts_load)
    {
        $this->_scripts_load = ( is_array($scripts_load) ? $scripts_load : array() );
    }

    function merge_scripts()
    {
        return array_unique(array_merge($this->_scripts_default, $this->_scripts_load));
    }
    
    // Styles
    function set_styles($config)
    {
        // Set Styles to load
        if(array_key_exists('styles', $config)) $this->set_styles_load($config['styles']);
        // Merge styles to load and defaults
        $this->_styles = $this->merge_styles();
    }

    function set_styles_load($styles_load)
    {
        $this->_styles_load = ( is_array($styles_load) ? $styles_load : array() );
    }
    
    function merge_styles()
    {
        return array_unique(array_merge($this->_styles_default, $this->_styles_load));
    }
    
    // Header
    function set_header($header=FALSE)
    {
        if($header) $this->_header = $header;
    }
    // Footer
    function set_footer($footer=FALSE)
    {
        //if($footer) $this->_footer = $footer;
        
       // $data['footer'] = $this->_footer;
        // $this->_template_footer = $this->_ci->config->item('footer', 'template');
        
        
        var_dump($this->_template_footer); die();
        
        
        // load
        
        // merge
        
        
    }
    
    

    function set_footer_load($scripts_load)
    {
        //$this->_scripts_load = ( is_array($scripts_load) ? $scripts_load : array() );
    }

    function _merge_scripts()
    {
        //return array_unique(array_merge($this->_scripts_default, $this->_scripts_load));
    }
    
    
    
    
    
    
    
    
    // Over ride ( do not load ) theme parts
    function set_theme_parts($config)
    {
        // Theme parts to over ride
        if(array_key_exists('theme_parts_omit', $config)) $this->_theme_parts_omit = $config['theme_parts_omit'];
    }

    
    // --------------------------------------------------------------------

    /**
        * Build the entire HTML output combining partials, layouts and views.
        *
        * @access	public
        * @param	string
        * @return	void
        */
    public function build($view, $data = array(), $return = FALSE)
    {

        // Setup
        $this->initialize(@$data['template_data']);

        // Disable IE7's constant cacheing!!
        $this->_ci->output->set_header('Expires: Sat, 01 Jan 2000 00:00:01 GMT');
        $this->_ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
        $this->_ci->output->set_header('Cache-Control: post-check=0, pre-check=0, max-age=0');
        $this->_ci->output->set_header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
        $this->_ci->output->set_header('Pragma: no-cache');

        // Let CI do the caching instead of the browser
        //$this->_ci->output->cache($this->cache_lifetime);

       $data['scripts'] = $this->_scripts_html;
       $data['styles'] = $this->_styles_html;
       $data['header'] = $this->_header;
       $data['footer'] = $this->_footer;

        $body = '';
        foreach($this->_theme_parts as $part){
            if($part !== 'view' && !in_array($part, $this->_theme_parts_omit)){
                $body .= $this->_ci->load->view($this->_theme_path.$part, $data, true);
            }elseif ($part == 'view' ){
                $body .= $this->_ci->load->view($view, $data, true);
            }
        }

        // Want it returned or output to browser?
        if ( ! $return )
        {
            $this->_ci->output->set_output($body);
        }

        return $this->_body;
    
    }
    
    
    /*
     * Set the default theme
     */
    public function set_default_theme()
    {
        // Set default theme
        foreach($this->_themes as $key => $value)
        {
            if($key == "default")
            {
                $this->_theme_default = $value;
                return TRUE;
            }
        }  
    }

    
    /*
     * Set the default scripts / styles to be loaded
     */
    public function set_defaults()
    {
        // Set default styles
        foreach($this->_template_styles as $key => $value)
        {
            if (key_exists("default", $value) && in_array($this->_theme, $value['default']))
            {
                $this->_styles_default[] = $key;
            }
        }

        // Set default scripts
        foreach($this->_template_scripts as $key => $value)
        {
            if (key_exists("default", $value) && in_array($this->_theme, $value['default']))
            {
                $this->_scripts_default[] = $key;
            }
        }
    }
    
    
    
    
    
    /**
        * Which theme are we using here?
        *
        * @access	public
        * @param	string	$theme	Set a theme for the template library to use
        * @return	void
        */
    public function set_theme($config)
    {
        // Get and set default theme
        $this->set_default_theme();

        $theme = array_key_exists('theme', $config) ? $config['theme'] : $this->_theme_default;

        foreach(array_keys($this->_themes) as $key){
            if ( $key == $theme )
            {
                // See if directory exists
                if ( file_exists( $this->_views_path.'themes/'.$theme ) )
                {
                    // Set theme path
                    $this->_theme_path = 'themes/'.$theme.'/';
                    // Set theme parts
                    $this->_theme_parts = $this->_themes[$key];
                    // See if view exists
                    foreach($this->_theme_parts as $part)
                    {
                        if(!$this->_find_view($part)) return FALSE; // Parts are missing
                    }
                    $this->_theme = $theme;
                    return TRUE;
                }
            }
        }
        return FALSE;
    }
    
    
    public function _find_view($view_name)
    {
        $target_file = $this->_views_path.$this->_theme_path.$view_name.'.php';
        if(($view_name=='view') || file_exists($target_file)) return TRUE;
    }
    
    
    
    /**
        * Which scripts are we including in the header/footer?
        *
        */
    public function build_scripts()
    {
        foreach( $this->_scripts as $script_name ){
            if ( array_key_exists( $script_name, $this->_template_scripts ) )
            {
                $this->_scripts_html .= "<script ".$this->build_tag_attributes($this->_template_scripts[$script_name])." ></script>\n";
            }
        }
        return $this;
    }
    
    
    /**
        * Which styles are we including?
        *
        */
    public function build_styles()
    {
        $this->merge_styles();
        foreach( $this->_styles as $style_name )
        {
            if ( array_key_exists( $style_name, $this->_template_styles ) )
            {
                $this->_styles_html .= "<link rel=\"stylesheet\" ".$this->build_tag_attributes($this->_template_styles[$style_name])." />\n";
            }
        }
        return $this;
    }
    
    
    
    /**
        * What are we including in the footer?
        *
        */
    public function build_footer()
    {
        $this->_footer_views();
        foreach( $this->_footer_views as $footer_view )
        {
            if ( $this->_find_view($footer_view['src']) )
            {
                $this->_footer_html .= $this->_ci->load->view($footer_view['src'], false, true);
            }
        }
        return $this;
    }  
    
    
    
    
    public function build_tag_attributes($attributes)
    {
        if(is_array($attributes))
        {
            $string = '';
            foreach($attributes as $key => $value)
            {
                if($key!=='default') $string .= $key."=\"".$value."\" ";
            }
            return $string;
        }
        return FALSE;
    }
 
}
